<template>
  <div class="pagination-container">
    <el-pagination
      background
      :page-size="pageSize"
      :total="total"
      :current-page.sync="currentPage"
      :layout="layout"
      :pager-count="pagerCount"
      @current-change="handleCurrentChange"
      v-if="total > 0">
    </el-pagination>
  </div>
</template>

<script>
import { pagination } from "../api/pagination";

export default {
  name: "CustomPagination",
  props: {
    url: {
      type: String,
      required: true
    },
    total: {
      type: Number,
      default: 0
    },
    pageSize: {
      type: Number,
      default: 10
    },
    layout: {
      type: String,
      default: "prev, pager, next, jumper"
    },
    pagerCount: {
      type: Number,
      default: 7,
      validator: value => value >= 5 && value <= 21 && value % 2 === 1
    }
  },
  data() {
    return {
      currentPage: this.getInitialPage()
    };
  },
  methods: {
    getInitialPage() {
      const savedPage = sessionStorage.getItem(`${this.url}pageCode`);
      return savedPage ? parseInt(savedPage) : 1;
    },
    handleCurrentChange(currentPage) {
      this.saveCurrentPage(currentPage);
      this.fetchPageData(currentPage);
    },
    saveCurrentPage(page) {
      sessionStorage.setItem(`${this.url}pageCode`, page);
    },
    async fetchPageData(page) {
      try {
        const res = await pagination({
          cUrl: this.url,
          pageNum: page
        });
        
        if (res.flag) {
          this.$emit("page-change", {
            data: res.data.list,
            currentPage: page
          });
        }
      } catch (error) {
        console.error("分页数据获取失败:", error);
        this.$message.error("分页数据加载失败");
      }
    }
  }
};
</script>

<style lang="less" scoped>
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 40px 0;
  padding: 0 20px;

  /deep/ .el-pagination {
    &.is-background {
      .btn-prev,
      .btn-next,
      .el-pager li {
        border-radius: 4px;
        margin: 0 4px;
        min-width: 36px;
        height: 36px;
        line-height: 36px;
        background-color: #f5f7fa;
        transition: all 0.3s;

        &:hover {
          color: #533ac2;
          background-color: #e1f3d8;
        }
      }

      .el-pager li {
        &.active {
          color: #fff;
          background-color: #533ac2;
          font-weight: normal;

          &:hover {
            color: #fff;
          }
        }
      }
    }

    .el-pagination__jump {
      margin-left: 10px;
    }
  }
}
</style>